#include "IO/opencv_impl.hpp"

OpenCVImpl::OpenCVImpl()
{
	param = Config1::Instance();
	switch(param->work_type)
	{
		case W_ImageOne:
			m_image = imread(param->src);	
			break;
		case W_ImagePairs:
			
			break;
		case W_ImageList:
			w_filelist.open(param->src.c_str());
			break;
		case W_Video:
			m_video.open(param->src);
			if(!m_video.isOpened())
				Log("Can not open the video",L_ERROR);
			break;
		case W_Calibration:
			m_video.open(param->src);
			if(!m_video.isOpened())
				Log("Can not open the video",L_ERROR);
			break;
		default:
			break;
	}
	if(param->output_src != string() && param->work_type == W_Video)
	{
		w_video.open(param->output_src,
			CV_FOURCC('M','P','E','G'),
			m_video.get(CV_CAP_PROP_FPS),
			Size(m_video.get(CV_CAP_PROP_FRAME_WIDTH), m_video.get(CV_CAP_PROP_FRAME_HEIGHT)));
		if(!w_video.isOpened())
				Log("Can not open the output video",L_ERROR);
	}
}


int OpenCVImpl::GetImage(Image& image)
{
	string line_c;
	string word_c;
	
	switch(param->work_type)
	{
		
		case W_ImagePairs:
		case W_ImageList:
			{
				getline(w_filelist, line_c, '\n');
				std::stringstream ss;
				ss.str(line_c);
				ss >> word_c;
				std::cout << word_c << std::endl;
				m_image = imread("Data/Normal/"+word_c + ".jpg");
				imshow("1",m_image);				
			}
			break;
		case W_Video:
			m_video >> m_image;
			break;		
		case W_Calibration:
			m_video >> m_image;
			break;
		case W_ImageOne:
			//cvtColor(m_image, m_image, CV_BGR2RGB);
			//image = Image(m_image.cols, m_image.rows, 3, (uint8_t*)m_image.data);
			//return 1;
			break;
		default:
			Log("This Type cannot use GetImage()",L_ERROR);
			break;
	}
	
	if(m_image.channels() == 3)
		cvtColor(m_image, m_image, CV_BGR2RGB);
	else
		cvtColor(m_image, m_image, CV_GRAY2RGB);
	Image(m_image.cols, m_image.rows, 3, (uint8_t*)m_image.data).CopyTo(image);
	
	if(!m_image.empty())
		return 1;
	return 0;
}

int OpenCVImpl::GetImageFromImage(Image& image, const string src)
{
	m_image = imread(src);
	//imshow("2",m_image);	
	if(m_image.channels() == 3)
		cvtColor(m_image, m_image, CV_BGR2RGB);
	else
		cvtColor(m_image, m_image, CV_GRAY2RGB);
	Image(m_image.cols, m_image.rows, 3, (uint8_t*)m_image.data).CopyTo(image);
		
	if(!m_image.empty())
		return 1;
	return 0;
}

void OpenCVImpl::Update(const Image& image)
{
	if((int)image.channel != 2)
		return;
	Mat out;
	cvtColor(Mat(image.height, image.width, CV_8UC3, image.data), out, CV_BGR2RGB);
	switch(param->work_type)
	{
		
		case W_ImageList:
			break;
		case W_Video:
		case W_Calibration:
			if(w_video.isOpened())
				w_video << out;
			break;
		case W_ImagePairs:
		case W_ImageOne:
			imwrite(param->output_src, out);
			break;
		default:
			Log("This Type cannot use Output",L_ERROR);
			break;
	}
}

int OpenCVImpl::WriteImage(const Image& image, const string src)
{
	if((int)image.channel != 2)
		return 0;
	Mat out;
	cvtColor(Mat(image.height, image.width, CV_8UC3, image.data), out, CV_BGR2RGB);
	if(imwrite(src, out))
		return 1;
	return 0;
}
